'use strict';
//日历核心算法
// 给定年月获取当月天数
function getMDay(y, m){ 
	var mday = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); 
	if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)//判断是否是闰月 
	   mday[1] = 29; 
	return mday[m - 1]; 
}

// 获取星期数 
function weekNumber(y, m, d) {
	var wk; 
	if (m <= 12 && m >= 1) { 
		for (var i = 1; i < m; ++i) { 
			d += getMDay(y, i); //
		} 
	} 
	/*根据日期计算星期的公式*/
	wk = (y - 1 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + d) % 7; 
	//0对应星期天，1对应星期一 
	return parseInt(wk); 
}

//加，减一个月,返回对应的 y ，m
function addAndDelOneMonth(y,m,mark){
	y = parseInt(y, 10)
	m = parseInt(m, 10)
	//加一个月
	if(mark == 'add'){
		if(m != 12){
			m++;
		}else{
			m=1;
			y++;
		}
	}else if(mark == 'del'){ //减一个月
		if(m != 1){
			m--;
		}else{
			m=12;
			y--;
		}
	}
	return {
		year : y, 
		month : m
	}
}

//获取当前时间
function getDateNow(){
	var myDate = new Date();
	return {
		year : myDate.getFullYear(),
		month : 1+parseInt(myDate.getMonth()),
		day : myDate.getDate()
	} 
}

//格式化日历
function formatDate(data,format){
	if(format != undefined && data){

		var yearLen = (format.indexOf('y') == -1 ? 0 : format.match(/[y]/ig).length)
		var monthLen = (format.indexOf('m') == -1 ? 0 : format.match(/[m]/ig).length)
		var dayLen = (format.indexOf('d') == -1 ? 0 : format.match(/[d]/ig).length)

		var val = format;
		if(yearLen > 4 || monthLen > 2 || dayLen > 2){
			console.error('format 格式错误，请参考 yyyy-mm-dd');
			return
		}
		var str = '';
		for(let i=0; i < yearLen; i++){
			str+='y';
		}
		val = val.replace(str,function(){
			data.year = data.year.toString();
			return data.year.substr(data.year.length - yearLen, yearLen);
		});

		if(monthLen == 2){
			val = val.replace('mm',data.month < 10? '0'+data.month : data.month);
		}else{
			val = val.replace('m',data.month);
		}
		if(dayLen == 2){
			val = val.replace('dd',data.day < 10? '0'+data.day : data.day);
		}else{
			val = val.replace('d',data.day);
		}
	}else if(data){
		var yearLen = 4;
		var monthLen = 2;
		var dayLen = 2;
		var val = data.year+'/'+data.month+'/'+data.day;
	}else{
		val = ''
	}

	return {
		val:val,
		show:{
			year: yearLen == 0 ? false : true,
			month: monthLen == 0 ? false : true,
			day: dayLen == 0 ? false : true
		}
	};
}

//1~9 加 0
function fliterNum(num){
	num = parseInt(num, 10);
	if(num < 10){
		num = '0'+num
	}else{
		num = num.toString();
	}
	return num;
}

//
export {getMDay, weekNumber, addAndDelOneMonth , formatDate, getDateNow, fliterNum};